let request = window.indexedDB.open("DGame", "1.0")
let db
let objectStore

request.onupgradeneeded = function (event) {
    db = event.target.result
    if (!db.objectStoreNames.contains('ReqShortcut')) {
        objectStore = db.createObjectStore('ReqShortcut', { keyPath: 'req' })
    }
}

function readAll( fn) {
    let objectStore = db.transaction('ReqShortcut').objectStore('ReqShortcut');
    objectStore.openCursor().onsuccess = function (event) {
        let cursor = event.target.result
        if (cursor) {
            fn(cursor.key, cursor.value)
            cursor.continue()
        } else {
            console.log('没有更多数据了！')
        }
    }
}

function read(id, fn) {
    let transaction = db.transaction(['ReqShortcut']);
    let objectStore = transaction.objectStore('ReqShortcut');
    let request = objectStore.get(id);

    request.onerror = function(event) {
        console.error('事务失败');
    };

    request.onsuccess = function( event) {
        fn(request.result)
    };
}

function update(id, val, fn) {
    let request = db.transaction(['ReqShortcut'], 'readwrite')
        .objectStore('ReqShortcut')
        .put({ id: 1, params: val });

    request.onsuccess = function (event) {
        fn()
    };

    request.onerror = function (event) {
        console.error('数据更新失败');
    }
}


function add(id, val, fn) {
    let request = db.transaction(['ReqShortcut'], 'readwrite')
        .objectStore('ReqShortcut')
        .add({ req: id, params: val});

    request.onsuccess = function (event) {
        fn()
    };

    request.onerror = function (event) {
        console.error('数据写入失败');
    }
}

function remove(id, fn) {
    let request = db.transaction(['ReqShortcut'], 'readwrite')
        .objectStore('ReqShortcut')
        .delete(id)

    request.onsuccess = function (event) {
        fn()
    }
}


function GetReqShortcuts() {
    let rs = localStorage.getItem("REQShortcut")
    rs = $.parseJSON(rs)
    if (rs === undefined || rs == null) {
        rs = {}
    }
    return rs
}

function DelReqShortcut(idx) {
    let rs = localStorage.getItem("REQShortcut")
    rs = $.parseJSON(rs)
    if (rs === undefined || rs == null) {
        rs = {}
    }
    delete rs[idx]
    localStorage.setItem("REQShortcut", JSON.stringify(rs))
}